package websocket

import (
	"gopkg.in/olahol/melody.v1"
	"time"
	"NicePay/yclient"
	"NicePay/model"
	"NicePay/utils"
	"encoding/json"
)

var (
	mel *melody.Melody
)

func Obtain() *melody.Melody {
	if mel == nil {
		mel = melody.New()
	}
	return mel
}

func (m *Msg) GetQr(uid uint) {
	id, data := yclient.Obtain().GetQrCode(m.GoodsName, m.Price)
	pay := &model.Payment{
		CreatedAt: time.Now(),
		GoodsName: m.GoodsName,
		Price:     m.Price,
		QrId:      id,
		Status:    model.Pending,
		Uid:       uid,
	}
	m.Data = data
	utils.Orm().Create(pay)
}

func BroadCast(b []byte) error {
	return mel.Broadcast(b)
}

func TradeSuccess(uid uint) {
	m := Msg{
		Tag:    "Trade",
		Data:   "success",
		Status: true,
	}
	resBytes, _ := json.Marshal(m)
	mel.BroadcastFilter(resBytes, func(s *melody.Session) bool {
		if suid, ok := s.Get("uid"); ok {
			return suid.(uint) == uid
		}
		return false
	})
}
